import axios, { AxiosResponse, InternalAxiosRequestConfig } from 'axios'
import { ElMessage } from 'element-plus'
import { GetStatusMsg } from '@/utils/constant'
import ResData from '@/utils/resData'

/**
 * @Description Axios 二次封装
 * @Date 2023/5/19 周五 15:11
 * @Author 酷奇 <vx：17685112557>
 */

const instance = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: import.meta.env.VITE_APP_TIME_OUT,
  /**
   * 允许跨域携带身份凭证
   */
  withCredentials: true,
  headers: {
    /**
     * 给后端区分开发环境
     */
    APP_KEY: import.meta.env.ENV_APP_KEY,
  },
})

//请求拦截器
instance.interceptors.request.use(
  (config: InternalAxiosRequestConfig<any>) => {
    // 发送请求前些什么

    //获取本地存储中的token
    // const [token] = useLocalStorageState('token')
    const token = localStorage.getItem('token')
    // token && (config.headers.Authorization = token)
    token && (config.headers.token = token)
    return config
  },
  (error: any) => {
    //请求失败做些什么
    return Promise.reject(error)
  },
)
//响应拦截器
instance.interceptors.response.use(
  (response: AxiosResponse<any, any>) => {
    return response.data
  },
  (error: any) => {
    //处理网络错误
    const status = error.response.status
    const msg = GetStatusMsg(status)
    ElMessage(msg)
    //服务器连结果都没有返回
    if (!window.navigator.onLine) {
      //断网处理：跳转断网页面/提示网络错误等等
      return
    }
    return Promise.reject(error)
  },
)

const setToken = (token: string) => {
  /*
   * 将 token注入到 Axios 的请求头中
   * 因为服务器是根据请求头中的token去验证接口的访问权限的
   * */
  instance.defaults.headers.common.token = token
}

// 定义GET
export const GET = async (url: string, params?: any): Promise<ResData<any>> => {
  return await instance.get(url, { params })
}

// 定义POST
export const POST = async (
  url: string,
  params?: any,
): Promise<ResData<any>> => {
  return await instance.post(url, params)
}

// 定义PUT
export const PUT = async (url: string, params?: any): Promise<ResData<any>> => {
  return await instance.put(url, params)
}

// 定义DELETE
export const DELETE = async (
  url: string,
  params?: any,
): Promise<ResData<any>> => {
  return await instance.delete(url, { params })
}
export default instance
